import { LoaderEmitter } from './loader-emitter.emitter';
import { Component, OnInit, Input } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';

@Component({
    selector: 'cmb-pace-loading',
    templateUrl: './pace-loading.component.html',
    styleUrls: ['./pace-loading.component.scss']
})
export class PaceLoadingComponent implements OnInit {

    private subscriber: Subscription;
    @Input() color: string;
    progress = 0;
    private totalRequests = 0;
    visibility = false;
    private thresHold = 60;
    anim1 = false;
    anim2 = false;

    constructor(private emitter: LoaderEmitter) {
        if (!this.subscriber) {
            this.subscriber = this.emitter.getEmitter().subscribe(data => {
                this.totalRequests = data.count;
                this.startLoader(data.action);
            });
        }
    }

    ngOnInit() {
        this.color = this.color ? this.color : '#6FCFD2';
    }

    private startLoader(action?: string): void {
        if (action === 'init' && this.totalRequests === 1) {
            this.show();
            this.progress = 60;
        } else if (action === 'end' && this.totalRequests === 0) {
            this.progress = 100;
            this.hide();
        }
    }

    handleProgressPercentage(flag: boolean): void {
        this.progress += 1;
    }

    private show(): void {
        this.anim2 = false;
        this.anim1 = true;
        this.visibility = true;
    }

    private hide(): void {
        this.anim1 = false;
        this.anim2 = true;
        setTimeout(() => {
            this.visibility = false;
        }, 800);
    }

}
